package com.guodx.study.springboot.d10.framework.async.config;

import com.guodx.study.springboot.d10.framework.async.core.AsyncExceptionHandler;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;


@Configuration
@EnableAsync
@EnableConfigurationProperties({AsyncProperties.class})
//@ConditionalOnProperty(name = "async.enabled", havingValue = "true", matchIfMissing = true)
@ConditionalOnProperty(prefix = "async", name = "enabled", havingValue = "true", matchIfMissing = true)
public class AsyncCopnfig implements AsyncConfigurer {

    @Autowired
    private AsyncProperties asyncProperties;

    @Override
    public Executor getAsyncExecutor() {
        /**
         * 如果超出容量限制，默认拒绝策略
         */
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

        executor.setCorePoolSize(asyncProperties.getCorePoolSize());
        executor.setMaxPoolSize(asyncProperties.getMaxPoolSize());
        executor.setQueueCapacity(asyncProperties.getQueueCapacity());
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(asyncProperties.getAwaitTerminateSeconds());
        executor.setThreadNamePrefix("AsyncThread-");
        // 拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize(); //如果不初始化，导致找到不到执行器
        return executor;
    }


    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new AsyncExceptionHandler();
    }
}
